﻿using Magicodes.ExporterAndImporter.Core.Models;
using Mapster;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ZhonTai.Admin.Core.Db;
using ZhonTai.Admin.Core.Dto;
using ZhonTai.Admin.Core.Helpers;
using ZhonTai.Admin.Services;
using ZhonTai.Admin.Services.Dict.Dto;
using ZhonTai.DynamicApi;
using ZhonTai.DynamicApi.Attributes;
using ZhonTai.Industry.Core.Consts;
using ZhonTai.Industry.Domain.PLCDevice;
using ZhonTai.Industry.Domain.WorkOrder;
using ZhonTai.Industry.Repositories.WorkOrder;
using ZhonTai.Industry.Resources;
using ZhonTai.Industry.Services.WorkOrder.Dto.Input;
using ZhonTai.Industry.Services.WorkOrder.Dto.Output;

namespace ZhonTai.Industry.Services.WorkOrder
{
    /// <summary>
    /// 工单服务
    /// </summary>
    [DynamicApi(Area = IndustryConsts.AreaName)]
    public class WorkOrderService : BaseService, IWorkOrderSerivice, IDynamicApi
    {
        private readonly IndustryLocalizer _industryLocalizer;
        private readonly IEHelper _iEHelper;
        private readonly IWorkOrderRepository _workOrderRepository;

        public WorkOrderService(IndustryLocalizer industryLocalizer, IEHelper iEHelper, IWorkOrderRepository workOrderRepository)
        {
            _industryLocalizer = industryLocalizer;
            _iEHelper = iEHelper;
            _workOrderRepository = workOrderRepository;
        }

        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<WorkOrderGetOutput> GetAsync(long id)
        {
            var output = await _workOrderRepository.GetAsync<WorkOrderGetOutput>(id);
            return output;
        }

        /// <summary>
        /// 列表查询
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IEnumerable<WorkOrderGetListOutput>> GetListAsync(WOrkOrderGetListInput input)
        {
            var list = await _workOrderRepository.Select
                .OrderByDescending(a => a.Id)
                .ToListAsync<WorkOrderGetListOutput>();
            return list;
        }

        /// <summary>
        /// 分页查询
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<PageOutput<WorkOrderGetPageOutput>> GetPageAsync(PageInput<WorkOrderGetPageInput> input)
        {
            var filter = input.Filter;
            var select = _workOrderRepository.Select
                .WhereDynamicFilter(input.DynamicFilter)
                .Count(out var total);
            if (input.SortList != null && input.SortList.Count > 0)
            {
                input.SortList.ForEach(sort =>
                {
                    select = select.OrderByPropertyNameIf(sort.Order.HasValue, sort.PropName, sort.IsAscending.Value);
                });
            }
            else
            {
                select = select.OrderBy(a => a.Sort);
            }
            var list = await select.OrderByDescending(c => c.Id)
              .Page(input.CurrentPage, input.PageSize)
              .ToListAsync<WorkOrderGetPageOutput>();
            //关联查询代码
            var data = new PageOutput<WorkOrderGetPageOutput> { List = list, Total = total };

            return data;
        }

        /// <summary>
        /// 下载导入模板
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [NonFormatResult]
        public async Task<ActionResult> DownloadTemplateAsync()
        {
            var fileName = _industryLocalizer["工单模板{0}.xlsx", DateTime.Now.ToString("yyyyMMddHHmmss")];
            return await _iEHelper.DownloadTemplateAsync(new WorkOrderImport(), fileName);
        }

        /// <summary>
        /// 下载错误标记文件
        /// </summary>
        /// <param name="fileId"></param>
        /// <param name="fileName"></param>
        /// <returns></returns>
        [HttpPost]
        [NonFormatResult]
        public async Task<ActionResult> DownloadErrorMarkAsync(string fileId, string fileName)
        {
            if (fileName.IsNull())
            {
                fileName = _industryLocalizer["工单下载错误标记{0}.xlsx", DateTime.Now.ToString("yyyyMMddHHmmss")];
            }
            return await _iEHelper.DownloadErrorMarkAsync(fileId, fileName);
        }

        /// <summary>
        /// 导出数据
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [NonFormatResult]
        public async Task<ActionResult> ExportDataAsync(ExportInput input)
        {
            using var _ = _workOrderRepository.DataFilter.DisableAll();
            var select = _workOrderRepository.Select;
            if (input.SortList != null && input.SortList.Count > 0)
            {
                select = select.SortList(input.SortList);
            }
            else
            {
                select = select.OrderBy(o => o.Sort);
            }
            var dataList = await select.WhereDynamicFilter(input.DynamicFilter).ToListAsync<WorkOrderExport>();
            //导出数据
            var fileName = input.FileName.NotNull() ? input.FileName : _industryLocalizer["数据工单-{0}列表{1}.xlsx", _industryLocalizer["当前工单"], DateTime.Now.ToString("yyyyMMddHHmmss")];

            return await _iEHelper.ExportDataAsync(dataList, fileName, _industryLocalizer["当前工单"]);
        }

        /// <summary>
        /// 导入数据
        /// </summary>
        /// <param name="file"></param>
        /// <param name="duplicateAction"></param>
        /// <param name="fileId"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ImportOutput> ImportDataAsync([Required] IFormFile file, int duplicateAction, string fileId)
        {
            var importResult = await _iEHelper.ImportDataAsync<WorkOrderImport>(file, fileId, async (importResult) =>
            {
                var importDataList = importResult.Data;
                List<string> orderCodeList = importDataList.Select(s => s.OrderCode).ToList();
                List<WorkOrderEntity> workOrderList = await _workOrderRepository.Where(w => w.State != 0).ToListAsync();
                var errorList = importResult.RowErrors;

                foreach (var workOrderImport in importDataList)
                {
                    var rowIndex = importDataList.ToList().FindIndex(o => o.Equals(workOrderImport)) + 2;
                    var workOrderEntity = workOrderList.Find(f => f.OrderCode == workOrderImport.OrderCode);
                    if (workOrderEntity != null)
                    {
                        var errorInfo = new DataRowErrorInfo()
                        {
                            RowIndex = rowIndex,
                        };
                        errorInfo.FieldErrors.Add(_industryLocalizer["导入工单"], _industryLocalizer["{0}已存在", workOrderImport.OrderCode]);
                        errorList.Add(errorInfo);
                    }
                    if (workOrderImport.ProductCode == "")
                    {
                        var errorInfo = new DataRowErrorInfo()
                        {
                            RowIndex = rowIndex,
                        };
                        errorInfo.FieldErrors.Add(_industryLocalizer["导入工单"], _industryLocalizer["{0}产品编号为空", workOrderImport.OrderCode]);
                        errorList.Add(errorInfo);
                    }
                }
                return importResult;
            });
            var importDataList = importResult.Data;
            var output = new ImportOutput()
            {
                Total = importDataList.Count
            };
            if (output.Total > 0)
            {
                //新增
                var insertImportDataList = importDataList.Where(w => w.Id == 0).ToList();
                var insertDataList = insertImportDataList.Adapt<List<WorkOrderEntity>>();
                output.InsertCount = insertDataList.Count;
                await _workOrderRepository.InsertAsync(insertDataList);

                //修改
                var updateImportDataList = importDataList.Where(w => w.Id > 0).ToList();
                if (duplicateAction == 1 && updateImportDataList.Count > 0)
                {
                    var updateImportDataIds = updateImportDataList.Select(e => e.Id).ToList();
                    var dbDataList = await _workOrderRepository.Where(a => updateImportDataIds.Contains(a.Id)).ToListAsync();
                    foreach (var dbData in dbDataList)
                    {
                        var data = updateImportDataList.Where(a => a.Id == dbData.Id).First();
                        data.Adapt(dbData);
                    }
                    output.UpdateCount = updateImportDataList.Count;
                    await _workOrderRepository.UpdateAsync(dbDataList);
                }
            }
            return output;
        }

        /// <summary>
        /// 新增
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<long> AddAsync(WorkOrderAddInput input)
        {
            var entity = Mapper.Map<WorkOrderEntity>(input);
            var id = (await _workOrderRepository.InsertAsync(entity)).Id;

            return id;
        }

        /// <summary>
        /// 更新
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPut]
        public async Task UpdateAsync(WorkOrderUpdateInput input)
        {
            var entity = await _workOrderRepository.GetAsync(input.Id);
            if (!(entity?.Id > 0))
            {
                throw ResultOutput.Exception("PLC设备配置不存在！");
            }

            Mapper.Map(input, entity);
            await _workOrderRepository.UpdateAsync(entity);
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpDelete]
        public async Task<bool> DeleteAsync(long id)
        {
            return await _workOrderRepository.DeleteAsync(id) > 0;
        }

        /// <summary>
        /// 软删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpDelete]
        public async Task<bool> SoftDeleteAsync(long id)
        {
            return await _workOrderRepository.SoftDeleteAsync(id);
        }

        /// <summary>
        /// 批量软删除
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        [HttpPut]
        public async Task<bool> BatchSoftDeleteAsync(long[] ids)
        {
            return await _workOrderRepository.SoftDeleteAsync(ids);
        }
    }
}